<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>流程部署</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <jsp:include page="/inc/head.jsp" flush="true"/>
    <link href="${basePath }/js/common/plugins/jui/themes/redmond/jquery-ui-1.9.2.custom.css" type="text/css" rel="stylesheet" />
    <link href="${basePath }/js/common/plugins/jui/extends/timepicker/jquery-ui-timepicker-addon.css" type="text/css" rel="stylesheet" />
    <link href="${basePath }/js/common/plugins/qtip/jquery.qtip.min.css" type="text/css" rel="stylesheet" />
    <jsp:include page="/inc/footer.jsp" flush="true"/>
    <script src="${basePath }/js/common/plugins/jui/jquery-ui-1.9.2.min.js" type="text/javascript"></script>
    <script src="${basePath }/js/common/plugins/qtip/jquery.qtip.pack.js" type="text/javascript"></script>
    <script src="${basePath }/js/common/plugins/html/jquery.outerhtml.js" type="text/javascript"></script>
    <script src="${basePath }/js/tip.js"></script>
    <script src="${basePath }/js/module/activiti/workflow.js"></script>
    <style>
        .content .box {
            border-top: 0;
        }
        .content #rowTable .bootstrap-table .fixed-table-toolbar .icon-refresh {
            padding: 3px 0;
        }
        .content .fixed-table-toolbar .bs-bars, .content .fixed-table-toolbar .columns,.content .fixed-table-toolbar .search {
            margin-top: 0;
        }
    </style>
</head>

<body class="hold-transition skin-blue sidebar-mini" style="overflow:hidden;">
<!-- Main content -->
<section class="content">
    <div id="toolbar" class="btn-group">
        <shiro:hasPermission name="upms:deploy:delete">
        <button id="btn_add" type="button" class="btn btn-default" onclick="delDeploy()">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除流程
        </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="upms:deploy:changeToModel">
        <button id="btn_delete" type="button" class="btn btn-default" onclick="changeModel()">
            <span class="glyphicon glyphicon-transfer" aria-hidden="true"></span>转换为Model
        </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="upms:deploy:deploy">
        <button id="btn_import" type="button" class="btn btn-default" onClick ="deployAct()">
            <span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>导入流程
        </button>
        </shiro:hasPermission>
        <div id="message" class="info" style="display:inline;background: deepskyblue"><b>提示：</b>点击xml或者png链接可以查看具体内容！</div>
    </div>

    <div id = "rowTable" class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-body table-responsive no-padding">
                    <table id="deployTable"></table>
                </div>
            </div>
        </div>
    </div>

    <div id="addActDeploy" class="modal fade bs-example-modal-lg addUpdateInfo" role="dialog" aria-labelledby="myLargeModalLabel">
        <div class="modal-dialog " role="document">
            <div class="modal-content" style="width: 600px;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleDeployLabel" >新增部署</h4>
                </div>
                <div class="modal-body" style="height: 300px;">
                    <fieldset id="deployFieldset" >
                        <div><b>支持文件格式：</b>zip、bar、bpmn、bpmn20.xml</div>
                        <form id="deployForm" method="post" enctype="multipart/form-data">
                            <div>
                                <input name="file" id="hotelImgFile" type="file" style="display: none"/>
                                <div class="input-append"><span style="white-space:pre;"></span>
                                    <input id="photoCover" type="text" class="form-control"style="float: left; width: 200px" >
                                    <span style="white-space:pre;"></span>
                                    <a class="btn btn-default" style="border-radius: 0px; width: 50px" onclick="$('input[id=hotelImgFile]').click();">浏览</a>
                                </div>
                            </div>
                        </form>
                    </fieldset>
                </div>
                <div class="modal-footer bg-info">
                    <button type="button" class="btn green" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="searchFile" onclick="saveDeploy();">确认</button>
                </div>
            </div>
        </div>
    </div>
</section>
<script type="text/javascript">
    var $table = $('#deployTable');
    $(function(){
        showTable();
    })



    function showTable() {
        $table.bootstrapTable({
            url: BASE_PATH+"/pcwindow/getActDeploy",
//                height: getHeight(),
            striped: true,
//            search: true,
            showRefresh: true,
            showColumns: true,
            minimumCountColumns: 2,
            clickToSelect: true,
            detailView: false,
            detailFormatter: 'detailFormatter',
            pagination: true,
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            searchOnEnterKey: true,
            idField: 'id',
            maintainSelected: true,
            toolbar: '#toolbar',
            columns: [
                {field: 'ck', align: 'center', checkbox: true},
                {field: 'id',title: 'id' },
                {field: 'deploymentId', title: 'DeploymentId', align: 'center'},
                {field: 'name', title: '名称', align: 'center'},
                {field: 'key', title: 'KEY', align: 'center'},
                {field: 'version', title: '版本号', align: 'center'},
                {field: 'xml', title: 'XML', align: 'center', formatter:"formatXML"},
                {field: 'picture', title: '图片', align: 'center', formatter:"formatPicture"},
                {field: 'deploymentTime', title: '部署时间', align: 'center', formatter:"formatTime"},
                {field: 'suspended', title: '是否挂起', align: 'center', formatter:"formatSuspended"},
                {field: 'action', title: '操作', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
            ],
            onLoadSuccess:function(data){
                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        });
        $table.bootstrapTable('resetView',{height:setHeight()});
    }
    /**
     * 表格高度自适应
     * @return
     * winTop 浏览器视口高度
     * header 顶部通栏
     * breadcrumb 面包屑
     * mainFooter 底部
     */
    function setHeight(){
        var winTop = $(window.top).height(),
            header = window.top.document.querySelector('.main-header').offsetHeight,
            breadcrumb =  window.top.document.querySelector('.breadcrumb').offsetHeight,
            mainFooter = window.top.document.querySelector('.main-footer').offsetHeight;
        return winTop-header-breadcrumb-mainFooter-10;
    }
    //查看XML功能
    function formatXML(value, row, index){
        return "<a target='_blank' href='${basePath}/pcwindow/readResource?processDefinitionId="+row.id+"&resourceType=xml' style='color:blue'>"+row.resourceName+"</a>";
    }
    //查看图片功能
    function formatPicture(value, row, index){
        return "<a target='_blank' href=\'javascript:showActivitiImage(\""+row.id+"\");\'>"+row.diagramResourceName+"</a>";
    }
    //转换部署时间
    function formatTime(value, row, index){
        return formatDateTime(value);
    }
    //点击激活状态
    function formatSuspended(value, row, index){
        if(value){
            return '<a href="javascript:;" onclick="updateSus(\'active\',\''+row.id+'\');" style="color:blue">激活</a>';
        }else{
            return '<a href="javascript:;" onclick="updateSus(\'suspend\',\''+row.id+'\');" style="color:blue">挂起</a>';
        }
    }

    //修改激活状态
    function updateSus(status,id){
        $.ajax({
            url:"${basePath}/pcwindow/update/"+status+"/"+id,
            type:'get',
            dataType:"json",
            success:function(data){
                confirmEvent(data.message);
                $table.bootstrapTable('refresh');
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                confirmEvent('系统开小差了，请稍后再试!');
            }
        })
    }

    //转换操作
    function actionFormatter(value, row, index){
        return [
            '<shiro:hasPermission name="upms:deploy:delete"> <a class="delete" href="javascript:;" onclick="delDeploy(\'' + row.deploymentId +'\')" data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a> </shiro:hasPermission>'
        ].join('');
    }

    //删除已经部署的流程
    function delDeploy(deploymentId){
        var ids = [];
        var flag = false;
        var rows = $table.bootstrapTable('getSelections');
        if(deploymentId==null||typeof(deploymentId)=="undefined"){
            if (rows.length == 0) {
                confirmEvent("请至少选择一条记录");
            }else{
                for (var i in rows) {
                    ids.push(rows[i].deploymentId);
                }
                flag = true;
            }
        }else{
            ids.push(deploymentId);
            flag = true;
        }
        if(flag){
            Ewin.confirm({ message: "您确定要删除此条记录？"}).on(function (e) {
                if(!e){
                    return;
                }else{
                    $.ajax({
                        type: 'post',
                        url: '${basePath}/pcwindow/delete',
                        data:{deploymentId:ids.join("-")},
                        success: function(result) {
                            confirmEvent("删除成功!");
                            $table.bootstrapTable('refresh');
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            confirmEvent('系统开小差了，请稍后再试!');
                        }
                    });
                }
            });
        }
    }

    //转化为model
    function changeModel(){
        var ids = [];
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length == 0) {
            confirmEvent("请至少选择一条记录");
        } else {
            for (var i in rows) {
                ids.push(rows[i].id);
            }

            $.ajax({
                url:"${ctx }/pcwindow/changeToModel/"+ids.join("-"),
                type:"get",
                success:function(result){
                    if(result){
                        confirmEvent("转换成功");
                    }else{
                        var str = "";
                        for(var key in result){
                            str += key+" ";
                        }
                        confirmEvent("转换失败");
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent('系统开小差了，请稍后再试!');
                }
            })

        }
    }

    function deployAct(){
        // 加载addmodel
        $('#addActDeploy').modal({
            keyboard: true
        });

        $(function(){
            $('input[id=hotelImgFile]').change(function(){
                $('#photoCover').val($(this).val());
            })
        })
    }

    //上传，流程文件
    function saveDeploy(){
        var data = $('#photoCover').val();
        if(data==null||data==""){
            confirmEvent("请选择要上传的文件");
            return;
        }
        //后缀名
        var lastName  = data.substring(data.lastIndexOf("."));
        var otherName = data.substring(0,data.lastIndexOf("."));
        //倒数第二个名字
        var secondlastName  = otherName.substring(otherName.lastIndexOf(".")+1);
        var secondName = secondlastName+lastName;
        console.log(secondName);
        if(lastName==".zip"||lastName==".bar"||lastName==".bpmn"||secondName=="bpmn20.xml"){
            $.ajax({
                url:"${basePath }/pcwindow/deploy",
                type:"post",
                data: new FormData($('#deployForm')[0]) ,
                dataType:"json",
                cache: false,
                processData: false,
                contentType: false,
                success:function(result){
                    if(result==0){
                        confirmEvent("部署失败");
                    }else{
                        confirmEvent("部署成功");
                        $('#addActDeploy').modal("hide")
                        $table.bootstrapTable('refresh');
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent('系统开小差了，请稍后再试!');
                }
            })
        }else{
            confirmEvent("请确认上传的文件格式");
            return;
        }
    }
</script>
</body>
</html>
